let _Vue = null

export default class VueRouter {
    static install (Vue) {
        if (VueRouter.install.installed) {
            return
        }
        VueRouter.install.installed = true

        _Vue = Vue

        _Vue.mixin({
            beforeCreate () {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            }
        })
    }

    constructor (options) {
        this.options = options
        this.data = _Vue.observable({
            current: window.location.pathname
        })
        this.routeMap = {}
    }

    init () {
        this.initRouteMap()
        this.initComponents()
        this.initEvent()
    }

    initRouteMap () {
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        })
    }

    initComponents () {
        _Vue.component('router-link', {
            props: {
                to: String
            },
            render (h) {
                return h('a', {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickLink
                    }
                }, [this.$slots.default])
            },
            methods: {
                clickLink (e) {
                    history.pushState({}, '', this.to)
                    this.$router.data.current = this.to
                    e.preventDefault()
                }
            }
        })

        _Vue.component('router-view', {
            render (h) {
                return h(this.$router.routeMap[this.$router.data.current])
            }
        })
    }

    initEvent () {
        window.addEventListener('popstate', () => {
            this.data.current = window.location.pathname
        })
    }
}